package com.dragon.graduation.user.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.bean.BeanCopy;
import com.dragon.config.crossConfig.NoToken;
import com.dragon.config.exception.exception.GlobalException;
import com.dragon.exception.GraduationException;
import com.dragon.graduation.student.entity.StudentEntity;
import com.dragon.graduation.student.service.StudentService;
import com.dragon.graduation.teacher.entity.TeacherEntity;
import com.dragon.graduation.teacher.service.TeacherService;
import com.dragon.graduation.user.controller.dto.UserAddDTO;
import com.dragon.graduation.user.controller.dto.UserLoginDTO;
import com.dragon.graduation.user.controller.dto.UserSearchDTO;
import com.dragon.graduation.user.controller.dto.UserUpdateDTO;
import com.dragon.graduation.user.controller.vo.UserLoginVO;
import com.dragon.graduation.user.controller.vo.UserVO;
import com.dragon.graduation.user.entity.UserEntity;
import com.dragon.graduation.user.service.UserService;
import com.dragon.jwt.JwtUtil;
import com.dragon.md5.Md5Encrypt;
import com.dragon.results.page.ResultPage;
import com.dragon.results.result.HttpResult;
import com.dragon.util.MyPage;
import com.dragon.util.WrapperUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author dragon
 * @since 2025-02-28 21:23:44
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Api(tags = "用户表 相关接口")
public class UserController {

    private final UserService userService;
    private final TeacherService teacherService;
    private final StudentService studentService;

    @PostMapping("add")
    @ApiOperation("1]用户表添加")
    @ApiOperationSupport(order = 1)
    @NoToken
    public HttpResult<String> add(@RequestBody UserAddDTO addDTO) {
        UserEntity entity = UserAddDTO.to(addDTO, UserEntity.class);
        entity.setPassword(Md5Encrypt.encryptPassword(entity.getUserName(), entity.getPassword()));
        userService.save(entity);

        return HttpResult.ok("添加成功");
    }

    @PostMapping("update")
    @ApiOperation("2]用户表修改")
    @ApiOperationSupport(order = 2)
    public HttpResult<String> update(@RequestBody UserUpdateDTO updateDTO) {
        UserEntity entity = userService.getById(updateDTO.getId());
        Assert.isFalse(ObjectUtils.isEmpty(entity), () -> new GlobalException("要修改的数据不存在"));
        entity = UserUpdateDTO.to(updateDTO, UserEntity.class);
        userService.updateById(entity);
        return HttpResult.ok("修改成功");
    }

    @PostMapping("search")
    @ApiOperation("3]用户表分页查询")
    @ApiOperationSupport(order = 3)
    public HttpResult<ResultPage<List<UserVO>>> search(@RequestBody UserSearchDTO searchDTO) {
        QueryWrapper<UserEntity> queryWrapper = WrapperUtil.constructWrapper(searchDTO, UserEntity.class);

        Page<UserEntity> entityPage = MyPage.setPage(UserEntity.class, searchDTO.getPage());
        Page<UserEntity> page = userService.page(entityPage, queryWrapper);
        ResultPage<List<UserVO>> resultPage = MyPage.copyPage(page, UserVO.class);
        return HttpResult.okForData(resultPage);
    }

    @PostMapping("delete")
    @ApiOperation("4]用户表删除")
    @ApiOperationSupport(order = 4)
    public HttpResult<String> delete(@RequestBody List<Integer> idList) {
        userService.removeByIds(idList);
        return HttpResult.ok("删除成功");
    }

    @PostMapping("login")
    @ApiOperation("5]登录")
    @ApiOperationSupport(order = 5)
    @NoToken
    public HttpResult<UserLoginVO> login(@RequestBody UserLoginDTO loginDTO) {
        QueryWrapper<UserEntity> wrapper = WrapperUtil.constructWrapper(loginDTO, UserEntity.class);
        UserEntity entity = userService.getOne(wrapper);
        if (ObjectUtils.isEmpty(entity)) {
            throw new GraduationException("用户不存在");
        }
        if (!entity.getPassword().equals(Md5Encrypt.encryptPassword(loginDTO.getUserName(), loginDTO.getPassword()))) {
            throw new GraduationException("密码错误");
        }

        //登录成功
        UserVO accountVO = UserVO.to(entity, UserVO.class);

        if (accountVO.getRole() == 2) {
            //学生
            StudentEntity student = studentService.findByUserId(accountVO.getId());
            if (ObjectUtils.isNotEmpty(student)) {
                accountVO.setRoleId(student.getId());
            }
        } else if (accountVO.getRole() == 3) {
            //教师
            TeacherEntity teacher = teacherService.getByUserId(accountVO.getId());
            if (ObjectUtils.isNotEmpty(teacher)) {
                accountVO.setRoleId(teacher.getId());
            }
        } else {
            //管理员
            accountVO.setRoleId(accountVO.getId());
        }
        String sign = JwtUtil.sign(accountVO);
        UserLoginVO accountLoginVO = UserLoginVO.to(entity, UserLoginVO.class);
        accountLoginVO.setToken(sign);
        return HttpResult.okForData(accountLoginVO);
    }

    @GetMapping("list")
    @ApiOperation("6]获取所有用户")
    @ApiOperationSupport(order = 6)
    public HttpResult<List<UserVO>> list() {
        List<UserEntity> list = userService.list();
        List<UserVO> result = BeanCopy.copyList(list, UserVO.class);
        return HttpResult.okForData(result);
    }

}
